package com.michale.admin.controller.system;

import com.michale.admin.controller.tool.BaseController;
import com.michale.common.annotation.Log;
import com.michale.common.constants.UserConstant;
import com.michale.common.domain.permissions.UserEntity;
import com.michale.common.domain.security.LoginUserDetail;
import com.michale.common.enmus.BusinessType;
import com.michale.common.properties.MichaleProperties;
import com.michale.common.result.AjaxResult;
import com.michale.common.utils.String.StringUtils;
import com.michale.common.utils.file.FileUploadUtils;
import com.michale.common.utils.file.MimeTypeUtils;
import com.michale.common.utils.security.SecurityUtils;
import com.michale.framework.config.server.ServerConfig;
import com.michale.framework.security.service.TokenService;
import com.michale.system.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @author michale
 * @apiNote 个人中心
 */
@Api(tags = "个人中心")
@RestController
@RequestMapping("system/user")
public class ProfileController extends BaseController {
    @Resource
    private UserService userService;
    @Resource
    private TokenService tokenService;
    @Resource
    private MichaleProperties michaleProperties;
    @Resource
    private ServerConfig serverConfig;

    /**
     * 查询个人详细信息
     *
     * @return 个人详细信息
     */
    @GetMapping("/profile/userProfile")
    public AjaxResult profile() {
        LoginUserDetail loginUser = getLoginUser();
        UserEntity user = loginUser.getUserEntity();
        AjaxResult ajax = AjaxResult.success(user);
        ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return ajax;
    }

    /**
     * 修改用户
     *
     * @param userEntity 个人信息
     */
    @PutMapping("/profile/updateProfile")
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    public AjaxResult updateProfile(@RequestBody UserEntity userEntity) {
        LoginUserDetail loginUser = getLoginUser();
        UserEntity user = loginUser.getUserEntity();
        userEntity.setUserName(user.getUserName());
        if (StringUtils.isNotEmpty(userEntity.getPhoneNumber())
                && UserConstant.NOT_UNIQUE.equals(userService.checkPhoneUnique(userEntity))) {
            return error("修改用户'" + userEntity.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(userEntity.getEmail())
                && UserConstant.NOT_UNIQUE.equals(userService.checkEmailUnique(userEntity))) {
            return error("修改用户'" + userEntity.getUserName() + "'失败，邮箱账号已存在");
        }
        userEntity.setUserId(user.getUserId());
        userEntity.setPassword(null);
        userEntity.setAvatar(null);
        userEntity.setDeptId(null);
        if (userService.updateUserProfile(userEntity) > 0) {
            // 更新缓存用户信息
            user.setNickName(userEntity.getNickName());
            user.setPhoneNumber(userEntity.getPhoneNumber());
            user.setEmail(userEntity.getEmail());
            user.setSex(userEntity.getSex());
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     *
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/profile/updateUserPwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword) {
        LoginUserDetail loginUser = getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return error("新密码不能与旧密码相同");
        }
        UserEntity userEntity = loginUser.getUserEntity();
        userEntity.setPassword(newPassword);
        if (userService.restPossWord(userEntity) > 0) {
            // 更新缓存用户密码
            loginUser.getUserEntity().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     *
     * @param file 文件
     */
    @PostMapping("/profile/uploadAvatar")
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            LoginUserDetail loginUser = getLoginUser();
            String fileName = FileUploadUtils.upload(michaleProperties.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            String avatar = serverConfig.getUrl() + fileName;
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar) > 0) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUserEntity().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }
}
